<?php

namespace app\admin\controller;

use app\admin\exception\AdminException;
use app\common\entity\Export;
use app\common\entity\MywalletLog;
use app\common\shop\AddressModel;
use app\common\shop\OrderGoodsModel;
use app\common\shop\OrderModel;
use app\common\shop\ShopGoodsModel;
use app\common\shop\ShopGroupModel;
use app\common\shop\UserLevelModel;
use think\Db;
use think\Request;
use app\common\entity\User;

class Goodsorders extends Admin {
    /**
     * [拼团]
     * @param
     * @return
     */
    public function group( Request $request ){
        $g = ShopGroupModel::alias('g')->field('g.*,u.nick_name,u.mobile,sg.title');
        $list = $g
            ->leftJoin('user u','u.id=g.uid')
            ->leftJoin('shop_goods sg','sg.id = g.goodsid')
            ->order('g.id desc')
            ->paginate(15, false, [
                'query' => $request->param()??[]
            ]);
        return $this->render('group',[
            'list'=>$list,
        ]);
    }

    /**
     * @power 内容管理|订单管理
     * @rank 0
     */
    public function index(Request $request) {

        $where=[];

        $status = trim( input('status'));
        if($status!=''){
            $where['o.status'] = $status;
            $map['status'] = $status;
        }
        // 拼团
        $groupid = input('groupid');
        if($groupid){
            $where['o.groupid'] =$groupid;
            $map['groupid'] = $groupid;
        }

        $paytype = trim( input('paytype'));
        if($paytype!=''){
            $where['o.paytype'] = $paytype;
            $map['paytype'] = $paytype;
        }
        $o = OrderModel::alias('o');
        $user = trim( input('user'));
        if($user!=''){
            // $where['u.nick_name|u.mobile|u.id'] = ['like','%'.$user.'%'];
            $o->where('u.nick_name|u.mobile|u.id','like','%'.$user.'%');
            $map['user'] = $user;
        }
        $ordersn = trim( input('ordersn'));
        if($ordersn){
            // $where['o.ordersn'] = ['like','%'.$ordersn.'%'];
            $o->where('o.ordersn','like','%'.$ordersn.'%');
            $map['ordersn'] = $ordersn;
        }
//        $list =
        $list = $o
            ->field('o.*,u.nick_name,u.mobile')
            ->join('user u','u.id = o.uid','left')
            ->where($where)
            ->order('o.id desc')
            ->paginate(15, false, [
                'query' => $request->param() ? $request->param() : []
            ]);

        foreach ($list as $key => $value) {
            $goods = OrderGoodsModel::getOrderGoods($value);
            $list[$key]['goods'] = $goods;
            $list[$key]['count_goods'] = count( $goods);
            $address =  unserialize($value['address_date']);

            $list[$key]['address'] =$address;
        }

        return $this->render('order',[
            'list'=>$list,
            'cate' => \app\common\entity\GoodsOrders::getAllCate(),
            'pay'=>(new OrderModel())->pay,
            'shoptype'=>(new ShopGoodsModel())->shoptype,
        ]);
        /*$search = input('get.search');
        $type = input('get.type');
        $status = input('get.types');
        $goodsCategoryModel = new \app\common\entity\GoodsOrders();
        //订单列表
        $lists = $goodsCategoryModel->getGoodsOrdersPages($search,$type,$status);

        foreach ($lists as $v) {
            $img = json_decode($v['goods_pic']);
            $v['img'] = $img[0];
        }
        return $this->render('index',[
            'lists'=>$lists,
            'cate' => \app\common\entity\GoodsOrders::getAllCate()
        ]);*/
    }


    /**
     * @power 内容管理|订单管理
     * @rank 0
     */
    public function diefa(Request $request) {

        $where=[];
        $ordersn = trim( input('ordersn'));
        if($ordersn){
            $where['o.ordersn'] = ['like','%'.$ordersn.'%'];
            $map['ordersn'] = $ordersn;
        }
        /*$status = trim( input('status'));
        if($status!=''){

        }*/
        $where['o.status'] = 1;
        $map['status'] = 1;
        // 拼团
        $groupid = input('groupid');
        if($groupid){
            $where['o.groupid'] =$groupid;
            $map['groupid'] = $groupid;
        }

        $paytype = trim( input('paytype'));
        if($paytype!=''){
            $where['o.paytype'] = $paytype;
            $map['paytype'] = $paytype;
        }

        $user = trim( input('user'));
        if($user!=''){
            $where['u.nick_name|u.mobile|u.id'] = ['like','%'.$user.'%'];
            $map['user'] = $user;
        }

        $list = OrderModel::alias('o')
            ->field('o.*,u.nick_name,u.mobile')
            ->join('user u','u.id = o.uid','left')
            ->where($where)
            ->order('o.id desc')
            ->paginate(15, false, [
                'query' => $request->param() ? $request->param() : []
            ]);

        foreach ($list as $key => $value) {
            $goods = OrderGoodsModel::getOrderGoods($value);
            $list[$key]['goods'] = $goods;
            $list[$key]['count_goods'] = count( $goods);
            $address =  unserialize($value['address_date']);

            $list[$key]['address'] =$address;
        }

        return $this->render('diefa',[
            'lists'=>$list,
            'cate' => \app\common\entity\GoodsOrders::getAllCate(),
            'pay'=>(new OrderModel())->pay,
            'shoptype'=>(new ShopGoodsModel())->shoptype,
        ]);
        /*$search = input('get.search');
        $type = input('get.type');
        $status = input('get.types');
        $goodsCategoryModel = new \app\common\entity\GoodsOrders();
        //订单列表
        $lists = $goodsCategoryModel->getGoodsOrdersPages($search,$type,$status);

        foreach ($lists as $v) {
            $img = json_decode($v['goods_pic']);
            $v['img'] = $img[0];
        }
        return $this->render('index',[
            'lists'=>$lists,
            'cate' => \app\common\entity\GoodsOrders::getAllCate()
        ]);*/
    }
    /**
     * [订单详情]
     * @return
     */
    public function orderdetail(){

        $id = input('id');
        $info = OrderModel::getInfo($id);
        $info['goods'] = OrderGoodsModel::getOrderGoods($info);
        $info['address'] = unserialize($info['address_date']);

        return $this->render('orderdetail', [
            'info' => $info,

        ]);
    }
    /**
     * [发货]
     * @return
     */
    public function send(){

        $id = input('id');
        $order = OrderModel::getInfo($id);
        if(empty($order)) return json(['code'=>1,'message'=>'订单错误']);
        if($order['status'] != 1) return json(['code'=>1,'message'=>'该订单不能发货']);
        if(!($expressname = input('expressname'))) return json(['code'=>1,'message'=>'请填写快递公司']);
        if(!($expressnumber = input('expressnumber'))) return json(['code'=>1,'message'=>'请填写快递单号']);
        OrderModel::sendOrder($id,['expressname'=>$expressname,'expressnumber'=>$expressnumber]);
        // 奖励
        UserLevelModel::commssion($order);
//        if($order['credit']>0){// 积分
//            MywalletLog::addLog($order['uid'], $order['credit'], 5, '购物奖励', 2, 1);
//        }
        return json(['code'=>0,'message'=>'发货成功','toUrl'=>url('/admin/goodsorders/index')]);
    }
    /**
     * [修改快递]
     * @param
     * @return
     */
    public function editexp( Request $request ){
        $id = input('id');
        $order = OrderModel::getInfo($id);
        if(empty($order)) return json(['code'=>1,'message'=>'订单错误']);
        if(!($expressname = input('expressname'))) return json(['code'=>1,'message'=>'请填写快递公司']);
        if(!($expressnumber = input('expressnumber'))) return json(['code'=>1,'message'=>'请填写快递单号']);
        OrderModel::where('id',$id)->setField(['expressname'=>$expressname,'expressnumber'=>$expressnumber]);
        return json(['code' => 0, 'toUrl' => url('/admin/goodsorders/index')]);
    }

    /**
     * @power 内容管理|订单管理@确认发货
     */
    public function edit($order_number) {
        $query = \app\common\entity\GoodsOrders::alias('o')->field('o.*,u.mobile as user_mobile');
        $query = $query->where('o.order_number',$order_number);
        $entity = $query->leftJoin("user u", 'u.id = o.user_id')
//            ->order('create_time', 'desc')
            ->find();

        if (!$entity) {
            $this->error('用户对象不存在');
        }

        return $this->render('edit', [
            'info' => $entity,
            'cate' => \app\common\entity\GoodsOrders::getAllCate()
        ]);
    }

    /**
     * @power 内容管理|订单管理@发货
     */
    public function update(Request $request, $order_number) {
        $res = $this->validate($request->post(), 'app\admin\validate\GoodsOrders');

        if (true !== $res) {
            return json()->data(['code' => 1, 'message' => $res]);
        }

        $entity = $this->checkInfo($order_number);

        $service = new \app\common\entity\GoodsOrders();
        $result = $service->updateGoodsOrders($entity, $request->post(),$service::TYPE_SEND);

        if (!$result) {
            throw new AdminException('保存失败');
        }

        return json(['code' => 0, 'toUrl' => url('/admin/goodsorders')]);
    }

    /*
     * 取消发货
     * */
    public function cancel(Request $request, $order_number){
        $entity = $this->checkInfo($order_number);

        $service = new \app\common\entity\GoodsOrders();
        $result = $service->updateGoodsOrders($entity, $request->post(),$service::TYPE_CANCEL);
        if (!$result) {
            throw new AdminException('取消失败');
        }

        return json(['code' => 0, 'message' => 'success']);
    }

    private function checkInfo($order_number) {
        $entity = \app\common\entity\GoodsOrders::where('order_number', $order_number)->find();
        if (!$entity) {
            throw new AdminException('对象不存在');
        }

        return $entity;
    }



}
